import java.net.*;
import java.nio.channels.*;
import java.io.IOException;

class Server
{
   InetSocketAddress serverAddr = null;

   public Server(int port)
   {
       serverAddr = new InetSocketAddress(port);
   }

   public void serve(IChannelHandler handler)
   {
      ServerSocketChannel serverSocket = null;
      SocketChannel channel = null;

      try
      {
         serverSocket = ServerSocketChannel.open();
         serverSocket.socket().bind(serverAddr);
         while(true)
         {
            handler.clientConnected(serverSocket.accept());
         }

      }

      catch (IOException e)
      {
         System.out.println(
            new StringBuilder()
            .append("Could not bind port ")
            .append(serverAddr.getPort())
            .append(":")
            .append(e.toString()));
      }
      finally
      {
         try
         {
            if (channel != null)
            {
               channel.close();
            }
            if (serverSocket != null)
            {
               serverSocket.close();
            }
         }
         catch (IOException e){}
      }
   }

}





